/**
 * 
 */
package com.pactera.util;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author liuqs
 * @version 
 * @since 2017年12月26日 上午11:57:15
 */
public class JsonUtil {
	private static final ObjectMapper MAPPER = new ObjectMapper();

	/**
	 * 将JSON字符串转成JAVA BEAN
	 * @param jsonStr
	 * @param toValueType
	 * @return
	 */
	public static <T> T convertValue2Bean(String jsonStr, Class<T> toValueType){
		if (StringUtils.isNotBlank(jsonStr) && toValueType != null){
			try {
				MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
				return MAPPER.readValue(jsonStr, toValueType);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 转化对象为JSON字符串
	 * @param toValueType
	 * @return
	 */
	public static String convertBean2Json(Object bean){
		try {
			MAPPER.setSerializationInclusion(Include.NON_NULL); 
			return MAPPER.writeValueAsString(bean);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**   
     * 获取泛型的Collection Type  
     * @param collectionClass 泛型的Collection   
     * @param elementClasses 元素类   
     * @return JavaType Java类型   
     * @since 1.0   
     */   
	 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   
	     return MAPPER.getTypeFactory().constructParametrizedType(collectionClass,collectionClass, elementClasses);   
	 }
	 
	 /**
	  * 将json字符串转成指定集合指定对象的集合列表
	  * @param jsonString
	  * @param collectionClass
	  * @param elementClasses
	  * @return
	  */
	 public static Collection<?> convertValue2List(String jsonString, Class<?> collectionClass,Class<?> elementClasses){
		 try {
			return MAPPER.readValue(jsonString, getCollectionType(collectionClass, elementClasses));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		 return null;
	 } 
	 
		/**
		 * 将JSON字符串转成JAVA BEAN
		 * @param jsonStr
		 * @param toValueType
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static Map<String, Object> convertBean2Map(Object bean){
			if (bean != null){
				try {
					return MAPPER.readValue(convertBean2Json(bean), Map.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}
}
